<template>
  <Dialog
    v-model="dialogVisible"
    width="600px"
    title="上传视频"
    :before-close="() => closeDialog()"
  >
    <el-form :model="form" ref="formRef" label-width="80px">
      <div class="w-full flex justify-between">
        <div class="w-40%">
          <!-- 仅保留视频上传 -->
          <el-form-item :label="t('video.video_id')">
            <div class="flex flex-items-center">
              <UploadVideo
                v-model:file-list="videoList"
                url="/common/uploadFile"
                ref="UploadFileRefVideo"
                upload-file-button-name="上传视频"
                :file-type="['mp4', 'mpeg', 'avi', 'wmv', 'mov', 'flv', 'swf', 'mkv']"
                :params="{ directory: 9 }"
                :limit="1"
                list-type="text"
                :show-file-list="true"
                @upload-success-res="handleUploadCallbackForVideo"
                @handle-remove-file="handleRemoveFile"
              />
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog()"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit()">{{ t('common.ok') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import UploadVideo from '@/components/UploadVideo/index.vue'
import { nextTick, ref } from 'vue'

const { t } = useI18n()
const emit = defineEmits(['exposeUploadData'])

interface UploadFile {
  name: string
  percentage?: number
  size?: number
  response?: unknown
  uid: number
  url?: string
}

const videoList = ref<Array<Record<string, any>>>([])

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({})

// 上传视频成功的回调 - 修复：使用统一的文件格式
const handleUploadCallbackForVideo = (val: any) => {
  // 确保与父组件使用相同的文件格式
  const fileItem = {
    id: val.id, // 保持ID字段用于更新
    url: val.url,
    name: val.name,
    type: 'video' // 添加type字段用于识别
  }
  videoList.value = [fileItem]
}

const handleRemoveFile = () => {
  videoList.value = [] // 清空视频列表
}

const submit = async () => {
  // 修复：支持修改/移除现有视频
  emit('exposeUploadData', videoList.value)
  closeDialog()
}

const closeDialog = () => {
  dialogVisible.value = false
}

// 修复：正确处理回显的视频数据格式
const getBackShow = async (row: Array<Record<any, any>>) => {
  // 确保传入的视频文件格式正确
  if (Array.isArray(row) && row.length > 0) {
    videoList.value = row.map((item) => ({
      id: item.id,
      url: item.url || item.response?.data?.url,
      name: item.name || item.response?.data?.name,
      type: 'video'
    }))
  } else {
    videoList.value = []
  }

  // 等待DOM更新以确保上传组件正确渲染
  await nextTick()
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
